package cn.easyutil.easyproject.easySpringboot.handler;

import cn.easyutil.easyproject.easySpringboot.bean.common.ResponseBody;
import cn.easyutil.easyproject.easySpringboot.exception.CommonException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.example.easyJavaUtil.LoggerUtil;
import cn.easyutil.easyproject.easySpringboot.context.Error;

/**
 * 异常统一处理类
 */
@RestControllerAdvice
public class ExceptionHandler {

    /**
     * 统一异常类返回值
     *
     * @param e 异常
     * @return 错误信息JSON字符串
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public ResponseBody exception(Exception e) {
        LoggerUtil.error(this.getClass(), "参数异常 : {}",e);
        LoggerUtil.error(this.getClass(), "", e);

        ResponseBody body = new ResponseBody();
        body.setCode(500);
        body.setErrorCode(-1);
        body.setErrorMsg(e.getMessage());

        // 处理dto验证异常
        if (e instanceof BindException) {
            BindException ex = (BindException) e;
            FieldError fieldError = ex.getBindingResult().getFieldError();

            body.setErrorCode(Error.biz_params_error.getCode());
            body.setErrorMsg(fieldError.getField() + "：" + fieldError.getDefaultMessage());
        }
        // 处理dto验证异常
        else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            FieldError fieldError = ex.getBindingResult().getFieldError();

            body.setErrorCode(Error.biz_params_error.getCode());
            body.setErrorMsg(fieldError.getField() + "：" + fieldError.getDefaultMessage());
        }
        // 处理自定义异常
        else if (e instanceof CommonException) {
            CommonException ex = (CommonException) e;
            body.setErrorCode(ex.getErrorCode().getCode());
            body.setErrorMsg(ex.getViewMessage());
        }
        else if(e instanceof NumberFormatException){
        	body.setErrorCode(Error.biz_params_error.getCode());
        	body.setErrorMsg(Error.biz_params_error.getRemark()+":"+e.getMessage());
        }
        else {
        	body.setErrorCode(Error.system_error.getCode());
        	body.setErrorMsg(Error.system_error.getRemark());
        }

        return body;
    }
}
